<?php
/**
 * PasswordController class file
 * -----------------------------
 *
 * LICENSE: BSD
 * @copyright  2009 Gemisoft
 * @author Deepak Pradhan <deepak.pradhan@gemisoft.com>
 * @link http://grbac.gemisoft.com/
 * @version $Id$
 * @since 0.1
 */
class PasswordController extends BaseController {
/**
 * User authentication
 * 1. pasword recovery
 * 2. passsord recovery confirm and reset
 **/

  public function actions() {
    return array('captcha'=>array('class'=>'CCaptchaAction', 'backColor'=>0xFFFFFF, 'testLimit'=>1),);
  }

  /**
   * Password reset request by user or email, send email for rest confirmation
   * @param username or email
   */
  public function actionForgot() {
    $user=new PasswordForgotForm('forgot');

    if(isset($_POST['PasswordForgotForm'])) {
      $user->setAttributes($_POST['PasswordForgotForm']);

      if($user->validate('forgot')) {
        $subject = 'Forgot Password Request';
        $emailText = $this->renderPartial('mail/forgot', array('form'=>$user), true, false);
        $this->grbac_sendEmail($to=$user->email, $subject, $emailText);

        $this->render('forgot_confirm',array('form'=>$user));
        return;
      }
    }

    $this->render('forgot',array('form'=>$user));
  }


  /**
   * confirm and validate password reset request
   * @param username
   * @param valid_code
   */
  public function actionValidate() {
    $user = PasswordForgotForm::model()->findByAttributes(array(
        'username'=>$_GET['username'],
        'valid_code'=>$_GET['valid_code']));

    if($user === null) {
      $this->render('validation_failed');
    }

    $this->setPageState('id', $user->id);
    $this->setPageState('valid_code', $user->valid_code);
    $this->render('password_reset', array('form'=>$user));
  }

  /**
   * resets user's password after successfull  validation in actionValidate()
   * requires valid page state variables to be set
   */
  public function actionResetPassword() {
    $id   = $this->getPageState('id');
    $code = $this->getPageState('valid_code');

    if( ($id === null) || ($code === null) ) {
      $this->render('password_reset_failed'); return;
    }

    $user = PasswordForgotForm::model()->findByAttributes(array('id'=>$id, 'valid_code'=>$code));
    $user->scenario ='resetPassword';

    if ($user === null) {
      $this->render('password_reset_failed'); return;
    }

    if(isset($_POST['PasswordForgotForm'])) {
      $user->setAttributes($_POST['PasswordForgotForm']);
      if($user->validate('resetPassword')) {
        $user->valid_code = null;
        $salt = date("YmdH",strtotime($user->created));
        $user->password = $this->grbac_crypt($user->algo,$user->passwordNew,$salt);
        if ($user->save()) {
          $this->render('password_reset_success'); return;
        }
      }
    }
    $this->render('password_reset', array('form'=>$user));
  }
}
